package com.lagou.controller;

import com.lagou.pojo.Token;
import com.lagou.service.AuthCodeService;
import com.lagou.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private AuthCodeService authCodeService;
	@Autowired
	private TokenService tokenService;

	/**
	 * 注册
	 */
	@RequestMapping("/registry/{email}/{password}/{code}")
	public boolean register(@PathVariable("email") String email, @PathVariable String password, @PathVariable("code") String code, HttpServletResponse response) {
		boolean rightAuthCode = authCodeService.isRightAuthCode(email, code);
		if (!rightAuthCode) {
			return false;
		}
		String token = tokenService.addToken(email, password);
		Cookie cookie = new Cookie("token", token);
		//重要！
		cookie.setPath("/");
		response.addCookie(cookie);
		return true;
	}

	/**
	 * 登录
	 */
	@RequestMapping("/login/{username}/{password}")
	public String login(@PathVariable("username") String username, @PathVariable("password") String password, HttpServletResponse response) {
		if (!tokenService.isRegistered(username)) {
			return "未注册";
		}
		Token token = tokenService.findToken(username, password);
		if (token == null) {
			return "密码错误";
		}
		//更新token
		String uuid = UUID.randomUUID().toString();
		Cookie cookie = new Cookie("token", uuid);
		//重要！
		cookie.setPath("/");
		response.addCookie(cookie);
		token.setToken(uuid);
		tokenService.updateToken(token);
		return "登录成功";
	}

	@RequestMapping("/isRegistered/{email}")
	public boolean isRegistered(@PathVariable("email") String email) {
		return tokenService.isRegistered(email);
	}

	@RequestMapping("/info/{token}")
	public String info(@PathVariable("token") String token) {
		return tokenService.findEmail(token);
	}
}
